var totalFruit = function(tree){
  const map = new Map();
  let j = 0;
  let max = 1;
  for(let i = 0;i < tree.length;i++){
    map.set(tree[i],i);
   
    if(map.length > 2){
      let minIndex = tree.length - 1;
      for(const [fruit,index] of map){
        minIndex = Math.min(minIndex,index);
      }
      map.delete(tree[minIndex]);
      j = minIndex +1;
    }
    max =Math.max(max,i-j+1);
  }
  return max;
}